from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

from util.exception import ValidationError
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import render, HttpResponse, redirect
from apps.user.models import User, AuthorityPathModel


class MyPermission(MiddlewareMixin):
    def process_request(self, request):
        # 获取用户请求的url
        token = request.META.get("HTTP_X_ACCESS_TOKEN")
        yuan_info = self.__de_ser(token)
        username = yuan_info.get("username")
        user = User.objects.filter(username=username).first()
        if user:
            paths = AuthorityPathModel.objects.filter(authority=user.authority).values("path")
            forbid_list = []
            for path in paths:
                forbid_list.append(path.get("path"))
            forbid_list = ",".join(forbid_list)
            target_url = request.path.replace("/", "")
            forbid_list = forbid_list.replace("/", "")
            forbid_list = forbid_list.split(",")
            if target_url in forbid_list:
                return HttpResponse("没有权限")

    def __de_ser(self, mi_info):
        try:
            serializer = Serializer(settings.SECRET_KEY, settings.TOKEN_TIME)
            yuan_info = serializer.loads(mi_info)
        except Exception as e:
            yuan_info = {}
        return yuan_info
